package tankbb;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.util.Iterator;

public class Missile {

	public static final int MISSILE_SPD = 20;	//20 pixels per second
	public static final int MISSILE_WIDTH = 15;
	public static final int MISSILE_HEIGH = 15;

	private TankClient tc;
	
	int x, y;
	private boolean live = true;
	TankClient.Dir missile_dir;
	boolean good = true;
	
	
	public Missile(int x, int y, TankClient.Dir dir, TankClient tc, boolean good) {
		this.x = x;
		this.y = y;
		this.missile_dir = dir;
		this.tc = tc;
		this.good = good;
		
		new Thread(new MissilePaint()).start();
	}
	
	public void setDead(){
		this.live = false;
	}
	
	public boolean isLive(){
		return live;
	}
	
	public void draw(Graphics g){
		Color c = g.getColor();
		g.setColor(Color.RED);
		g.fillOval(x, y, Missile.MISSILE_WIDTH, Missile.MISSILE_HEIGH);
		g.setColor(c);
	}
	
	public boolean chkHit(int x, int y){
		Rectangle r_m = null;	//missile rectangle
		Rectangle r_t = null;	//tank rectangle
		Tank t = null;
		Iterator<Tank> it = null;
		
		r_m = new Rectangle(x - Missile.MISSILE_WIDTH/2, y - Missile.MISSILE_HEIGH/2, Missile.MISSILE_WIDTH, Missile.MISSILE_HEIGH);
		
		for(int i=0; i < tc.arr_t.size(); i++){
			it = tc.arr_t.iterator();
			while(it.hasNext()){
				t = it.next();
				r_t = t.getRec();
				if(r_m.intersects(r_t) && (this.good != t.good)){
					System.out.println("!!!!!");
					t.setDead();
					this.setDead();
					tc.arr_e.add(new Explode(x, y, this.tc));
					
					Tank.index_m--;
					Tank.index_t--;
					return true;
				}
			}
		}
		return false;
	}
	
	private class MissilePaint implements Runnable{

		public void run() {
			
			boolean flg = true;
			while (flg) {
				switch(missile_dir){
				case U:
					y -= MISSILE_SPD;
					break;
				case UR:
					x += MISSILE_SPD;
					y -= MISSILE_SPD;
					break;
				case R:
					x += MISSILE_SPD;
					break;
				case DR:
					x += MISSILE_SPD;
					y += MISSILE_SPD;
					break;
				case D:
					y += MISSILE_SPD;
					break;
				case LD:
					x -= MISSILE_SPD;
					y += MISSILE_SPD;
					break;
				case L:
					x -= MISSILE_SPD;
					break;
				case LU:
					x -= MISSILE_SPD;
					y -= MISSILE_SPD;
					break;
				}
				
				if(chkHit(x, y)){
					return;
				}
				
				try {
					Thread.sleep(50);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				
				if(x < -10 || y < 0 || x > TankClient.WIN_WIDTH || y > TankClient.WIN_HEIGH){
					flg = false;
					Tank.index_m--;
					setDead();
				}
			}
		}
	}
}
